#include "GetMACAddress.h"

//#ifndef WINCE
//	#define RETAILMSG(a,b)	
//#endif

TCHAR g_macaddress[200];

void IntToChar16( int num, TCHAR *c)
{
	switch ( num )
	{
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
		case 8:
		case 9:  *c = ('0')+ num; break;
		case 10: *c = ('A'); break;
		case 11: *c = ('B'); break;
		case 12: *c = ('C'); break;
		case 13: *c = ('D'); break;
		case 14: *c = ('E'); break;
		case 15: *c = ('F'); break;
	}
}

void IntToString16(int num, TCHAR* str)
{
 int i1;
 int i2;

 i1 = num & 0x0F;
 i2 = ( num & 0xF0 ) / 16;

 IntToChar16(i1, str+1);
 IntToChar16(i2, str);

 *(str+2) = 0;
}

TCHAR *GetMacAddress( int numberAdapter)
{
	//IP_ADAPTER_INFO AdapterInfo;
	HLOCAL hAdapterInfo;

	TCHAR *szMacAddress = NULL;
	//TCHAR tempStr[10] = {0};
	PIP_ADAPTER_INFO pAdapterInfo = NULL;//&AdapterInfo;
    PIP_ADAPTER_INFO pAInfo = NULL;//&AdapterInfo;
	ULONG ulSizeAdapterInfo = 0;
	DWORD dwReturnvalueGetAdapterInfo;
	UINT index=0;
	
	SetLastError(0);
	dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo );
		
	//Check whether the GetAdaptersInfo succeeded 
	if ( dwReturnvalueGetAdapterInfo == ERROR_BUFFER_OVERFLOW)
	{

		hAdapterInfo = LocalAlloc(LMEM_FIXED, ulSizeAdapterInfo);
		pAdapterInfo = (PIP_ADAPTER_INFO)LocalLock(hAdapterInfo);
		if (! pAdapterInfo )
		{
			//RETAILMSG(1,(L"Insufficient Memory\n "));
			goto ERROR_TAG;
		}

		//Try GetAdaptersInfo again
		SetLastError(0);	
		dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo);
		if (dwReturnvalueGetAdapterInfo != ERROR_SUCCESS)
		{
			//RETAILMSG(1,(L"Error in GetAdaptersInfo\n"));
			goto ERROR_TAG;
        }
	}

	//GetAdaptersInfo Failed 
	else if (dwReturnvalueGetAdapterInfo != ERROR_SUCCESS) 
	{
		//RETAILMSG(1,(L"Error in GetAdaptersInfo"));
		goto ERROR_TAG;
     
	}

	pAInfo = pAdapterInfo;
	while ( numberAdapter != 0 )
	{
		if ( pAInfo != NULL )
		{
			pAInfo = pAInfo->Next;
		}

        numberAdapter--;
	}

	if ( pAInfo == NULL )
	{
		//RETAILMSG(1,(L"PIP_ADAPTER_INFO is NULL after getAdapterInfo. Error Is:%d\n",GetLastError()));
		goto ERROR_TAG;
	}


	szMacAddress = g_macaddress;
	szMacAddress[0] = ('\0');

    for (index = 0; index < pAInfo->AddressLength; index++) 
	{
		IntToString16(pAInfo->Address[index],szMacAddress + 2*index);
	}

ERROR_TAG:

	if( pAdapterInfo != NULL )
	{
		LocalUnlock(hAdapterInfo);
		LocalFree(hAdapterInfo);
	}
	
	return szMacAddress;	
}
